package com.algorithm.ch1.cjm.design;

import java.util.Stack;

/**
 * @Author: Jie Ming Chen
 * @Date: 2018/9/13
 * @Version 1.0
 */
public class MinStack1 {

    private final Stack<Integer> stack;
    private long min = Long.MAX_VALUE;

    public MinStack1() {
        stack = new Stack<>();
    }

    /**
     * 往栈里面推送数据
     * @param x
     */
    public void push(int x) {
        if (stack.isEmpty()) {
            min = x;
        } else if (x <= min) {
            stack.push((int) min);
            min = x;
        }
        stack.push(x);
    }

    /**
     * 删除栈顶的元素
     */
    public void pop() {
        if (!stack.isEmpty() && stack.pop() == min) {
            if (stack.isEmpty()) {
                min = Long.MAX_VALUE;
            } else {
                min = stack.pop();
            }
        }
    }

    /**
     * 获取栈顶元素
     * @return
     */
    public int top() {
        return stack.peek();
    }

    /**
     * 检索栈中的最小元素
     * @return
     */
    public int getMin() {
        if (stack.isEmpty()) {
            throw new java.util.EmptyStackException();
        } else {
            return (int) min;
        }
    }

    public static void main(String[] args) {

        MinStack1 minStack = new MinStack1();
        minStack.push(-2);
        minStack.push(0);
        minStack.push(-3);

        System.out.println(minStack.stack.toString());
        minStack.getMin();
        minStack.pop();

        System.out.println(minStack.stack.toString());
        minStack.top();
        minStack.getMin();

        System.out.println(minStack.stack.toString());
    }

}
